import MySQLdb
import string
import logging
from tools import config

logging.basicConfig(level=logging.DEBUG,format = "%(created)-15s %(msecs)d %(levelname)8s %(thread)d %(name)s %(message)s")
log = logging.getLogger(__name__)

class DBConn :
	
	def __init__ (self) :
		self.debug = config.getDebug ()
		if self.debug :
			log.debug("__init__")
		"""initial stuff, connecting to database"""
		self.dbhost = config.getDBHost ()
		self.dbuser = config.getDBUser ()
		self.dbpass = config.getDBPass ()
		self.dbname = "pyhmon"
		self.db = MySQLdb.connect (host = self.dbhost, user = self.dbuser, passwd = self.dbpass, db=self.dbname)
		self.cursor=self.db.cursor()
	
	def insert (self, nodename, pluginname, time, value) :
		if self.debug :
			log.debug("insert")
		q = 'self.cursor.execute ("INSERT INTO ' + pluginname + " (node, time" 
		v = (nodename, str (int (time))) + tuple (string.split (value, " "))
		t = "%s"
		for i in range (2, len(v)) :
			q += ", value" + str(i-2)
		for i in range (1, len(v)) :
			t += ", %s"
		q += ") VALUES (" + t + ")\", " + str(v) + ")"
		eval(q)

	def minsert (self, nodename, pluginname, values) :
		if self.debug :
			log.debug("minsert")
		q = 'self.cursor.executemany ("INSERT INTO ' + pluginname + \
		" (node, time"
		data=[]
		for v in values :
			data.append ((nodename,) + v)
		for i in range (2, len(data[0])) :
			q += ", value" + str(i-2)
		t = "%s"
		for i in range (1, len(data[0])) :
			t += ", %s"
		q += ") VALUES (" + t + ')", data)'
		eval(q)

